<template>
  <div class="tablePageWarp">
    <div class="commonSelectWidth table-page-search-wrapper">
      <a-form layout="vertical" >
        <a-row :gutter="[16,0]">
          <a-col
            :md="4"
            :sm="24"
          >
            <!-- 车系名称 -->
            <a-form-model-item :label="$t('brandName')">
              <a-select
                v-model="queryParam.brandId"
                showSearch
                allow-clear
                :defaultActiveFirstOption="false"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+$t('brandName')"
                :maxTagCount="1"
                @change="refreshData(true)"
                style="width:100%; margin-bottom: 20px;"
              >
                <a-select-option
                  v-for="(item,index) in brandSeleList"
                  :key="'brand'+index"
                  :value="item.id"
                  :title="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 车型名称 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('vehicleModel')">
              <car-model-code-select
                mode="default"
                :query="{ time:instantUpdateTime, selectAll: true}"
                :has-all="false"
                :clear="true"
                v-model="queryParam.code"
                @change="refreshData(true)"
                @changeoption="(val,item) => queryParam.trimLevelName = item ? item.showName : undefined"
                style="width:100%;margin-bottom:20px"
              ></car-model-code-select>
            </a-form-model-item>
          </a-col>
          <!-- 数据来源-->
          <a-col :md="4" :sm="24">
            <a-form-model-item label="数据来源">
              <a-select
                v-model="queryParam.dataFrom"
                @change="refreshData(true)"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                showSearch
                placeholder="数据来源"
                allow-clear
                style="width:100%"
              >
                <a-select-option
                  v-for="(item, index) in configModelDataFrom"
                  :key="'dataFrom'+index"
                  :value="item.value"
                  :title="item.name"
                >{{ item.name }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item :label="$t('timeOfCreation')">
              <a-range-picker
                @change="selectDateRange"
                v-model="createTime"
                :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                }"
                style="width: 100%"
                :placeholder="['创建时间-开始','结束']"/>
            </a-form-model-item>
          </a-col>
          <!--创建人-->
          <a-col
            :md="4"
            :sm="24"
          >
            <a-form-model-item :label="$t('creator')">
              <a-select
                v-model="queryParam.createBy"
                showSearch
                allow-clear
                optionFilterProp="children"
                @change="refreshData(true)"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect')+ $t('creator')"
                :maxTagCount="1"
                style="width:100%"
              >
                <a-select-option
                  v-for="(item,index) in userList"
                  :key="'user'+index"
                  :value="item.id"
                  :title="item.name"
                >
                  {{ item.name + '('+item.account+')' }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col
            :lg="24"
            :sm="24"
          >
            <div class="searchBtns">
              <a-button-group>
                <auth-button type="primary" :auth="managePerms.model.view" @click="refreshData(true)">
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </auth-button>
                <a-button @click="initiSelectValue">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="1">
                      <auth-text :auth="managePerms.model.add" @click="handleAddEdit()">
                        {{ $t('new') }}
                      </auth-text>
                    </a-menu-item>
                    <a-menu-item key="2">
                      <auth-text :auth="managePerms.model.add" @click="copy(selectedRows)">
                        根据所选复制新建
                      </auth-text>
                    </a-menu-item>
                  </a-menu>
                </template>
                <auth-button type="primary">
                  <i class="iconfont icon-xinjian"></i>
                  {{ $t('new') }}
                </auth-button>
              </a-dropdown>
              <!-- <auth-button :auth="managePerms.model.add" @click="handleAddEdit()">
                <i class="iconfont icon-xinjian"></i>
                {{ $t('new') }}
              </auth-button> -->
              <auth-button :auth="managePerms.model.delete" @click="deleteList(selectedRows, ()=>{selectedRows=[]})" type="danger">
                <i class="iconfont icon-shanchu"></i>
                {{ $t('batchDelete') }}
              </auth-button>
              <auth-button  :auth="managePerms.model.import" @click="importVisible=true">
                {{ $t('import') }}
              </auth-button>
              <auth-button  :auth="managePerms.model.export" @click="exportXlsx" :loading="exporting">
                {{ $t('export') }}
              </auth-button>
              <auth-button
                :auth="managePerms.parts.sync"
                @click="sync"
                :loading="synchronizing"
              >{{ $t('数据更新') }}</auth-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <s-table
      ref="table"
      class="h100 withMinHeightTbodyBox"
      :row-selection="{ selections:true,selectedRowKeys:selectedRowKeys,getCheckboxProps:getCheckboxProps, onChange: onTableSelectChange }"
      :rowKey="(record, index) => record.id +'-' + index"
      :columns="columns"
      :data="loadData"
      :scrollX="1900"
      :getPopupContainer="getPopupContainer"
    >
      <template slot-scope="text,record" slot="company">
        <table-ellipsis :text="$store.getters.getDictCodeObj('companyDictCode')[record.model.company]" key="t-company"></table-ellipsis>
      </template>
      <template slot-scope="text,record" slot="power">
        <table-ellipsis :text="$store.getters.getDictCodeObj('powerTypeDictCode')[record.model.power]" key="t-power"></table-ellipsis>
      </template>
      <template slot-scope="text,record" slot="saleArea">
        <table-ellipsis :text="$store.getters.getDictCodeObj('saleAreaDictCode')[record.model.saleArea]" key="t-saleArea"></table-ellipsis>
      </template>
      <template slot-scope="text,record" slot="dataFrom">
        <table-ellipsis :text="$store.getters.getDictCodeObj('configModelDataFromDictCode')[record.dataFrom]" key="t-dataFrom"></table-ellipsis>
      </template>
      <template slot-scope="text" v-for="(column,index) in columns.filter(item => !item.special)" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text||'_'" :key="'model'+index"></table-ellipsis>
      </template>
      <template
        slot="stereotype"
        slot-scope="text,record"
      >
        <a @click="showCarModelDetail(record)">
          <table-ellipsis :text="text"></table-ellipsis>
        </a>
      </template>
      <template
        slot="ecuList"
        slot-scope="text,record"
      >
        <a
          @click="showCarModelDetail(record)"
          v-if="Array.isArray(record.model.ecuIds)&&record.model.ecuIds.length"
        >
          <i class="iconfont icon-ecu"></i>
          <span style="font-weight:bolder"> {{ record.model.ecuIds.length }}</span>
        </a>
        <div v-else>
          <i class="iconfont icon-ecu"></i>
          <span> 0</span>
        </div>
      </template>
      <template
        slot="managedServices"
        slot-scope="text,record"
      >
        <a
          @click="showCarModelDetail(record,'managedServices')"
          v-if="record.model.serviceCount"
        >
          <i class="iconfont icon-yuyuefuwu"></i>
          <span style="font-weight:bolder"> {{ record.model.serviceCount }}</span>
        </a>
        <div v-else>
          <i class="iconfont icon-yuyuefuwu"></i>
          <span> 0</span>
        </div>
      </template>
      <template
        slot="createTime"
        slot-scope="text"
      >
        <table-ellipsis v-if="text" :text="$options.filters.moment(text)"></table-ellipsis>
      </template>
      <span
        slot="action"
        slot-scope="text, record"
        class="tableOperateSty"
        style="display: flex;"
      >
        <!-- <operation-menu
          :menus="getTbRowMenus(record)"
          @clickaction="(key)=>{
            doAction(key,record)
          }"
        ></operation-menu> -->
        <auth-button :auth="managePerms.model.serviceManage" @click="manageService(record)" type="primary" :ghost="true" size="small">{{ $t('managedServices') }}</auth-button>
        <auth-button :auth="managePerms.model.configEcu" @click="ecuConfig(record)" type="primary" :ghost="true" size="small">{{ $t('ecuConfig') }}</auth-button>
        <auth-button :auth="managePerms.model.edit" @click="handleAddEdit(record)" type="primary" :ghost="true" size="small"><i class="iconfont icon-xiugai"/>{{ $t('edit') }}</auth-button>
      </span>
    </s-table>
    <a-modal
      v-model="importVisible"
      title="导入车型"
      width="1000px"
      dialogClass="createFormStyle"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }"
    >
      <template slot="footer">
        <a-button @click="importVisible = false" type="primary">{{ $t('back') }}</a-button>
      </template>
      <div>
        <a-input
          class="formFileInput"
          :placeholder="$t('formatFiles')"
          readOnly
          :value="importFile"
          style="width:400px;margin-right: 10px"
        >
          <template #addonAfter>
            <i class="iconfont icon-shangchuan" @click="$refs.upload.uploadDo()"></i>
          </template>
        </a-input>
        <a-button
          @click="downloadTemplate"
          :loading="downloading"
        >{{ $t('downloadTemplate') }}</a-button>
        <div>
          <template v-if="uploadRes.fail.length > 0">
            <h4 style="margin-top:20px;color:red">失败明细(共{{uploadRes.failCount}}条)：</h4>
            <a-table
              ref="importFailTable"
              class="h100 withMinHeightTbodyBox"
              :rowKey="(record, index) => 'fail-' + index"
              :columns="importFailColumns"
              :data-source="uploadRes.fail"
              :scroll="{x:800,y:350}"
              :pagination="false"
            >
              <template slot-scope="text,record" slot="company">
                <table-ellipsis :text="$store.getters.getDictCodeObj('companyDictCode')[record.model.company]" key="t-company"></table-ellipsis>
              </template>
              <template slot-scope="text,record" slot="power">
                <table-ellipsis :text="$store.getters.getDictCodeObj('powerTypeDictCode')[record.model.power]" key="t-power"></table-ellipsis>
              </template>
              <template slot-scope="text,record" slot="saleArea">
                <table-ellipsis :text="$store.getters.getDictCodeObj('saleAreaDictCode')[record.model.saleArea]" key="t-saleArea"></table-ellipsis>
              </template>
              <span slot="message" slot-scope="message" style="color:red;white-space: pre-line">
                {{ message }}
              </span>
            </a-table>
          </template>
          <template v-if="uploadRes.success.length > 0">
            <h4 style="margin-top:20px;">导入成功(共{{uploadRes.successCount}}条)：</h4>
            <a-table v-if="uploadRes.success.length > 0"
                     ref="importSuccessTable"
                     class="h100 withMinHeightTbodyBox"
                     :rowKey="(record, index) => 'suc-' + index"
                     :columns="importSuccessColumns"
                     :data-source="uploadRes.success"
                     :scroll="{x:800,y:350}"
                     :pagination="false"
            >
              <template slot-scope="text,record" slot="company">
                <table-ellipsis :text="$store.getters.getDictCodeObj('companyDictCode')[record.model.company]" key="t-company"></table-ellipsis>
              </template>
              <template slot-scope="text,record" slot="power">
                <table-ellipsis :text="$store.getters.getDictCodeObj('powerTypeDictCode')[record.model.power]" key="t-power"></table-ellipsis>
              </template>
              <template slot-scope="text,record" slot="saleArea">
                <table-ellipsis :text="$store.getters.getDictCodeObj('saleAreaDictCode')[record.model.saleArea]" key="t-saleArea"></table-ellipsis>
              </template>
            </a-table>
          </template>
        </div>
        <!-- 来自文件上传 -->
        <local-upload
          ref="upload"
          :domView="false"
          @showFileObj="showFileObj"
          :accept="['.xls','.xlsx']"
        ></local-upload>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
import APopover from 'ant-design-vue/es/popover'
import FilterBoxCollection from '@/components/SelfComponents/FilterBoxCollection'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import { minxinDrawerUse } from '@/utils/mixin'
import NewEditModel from './components/NewEditModel.vue'
import ModelDetail from './components/ModelDetail'
import NewEditBrand from './components/NewEditBrand.vue'
import ManagedServicesList from './components/ManagedServicesList.vue'
import ConfigEcu from './components/ConfigEcu.vue'
import { STable } from '@/components'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import { managePerms } from '@/config/permission/index'
import { modelListTbColumns } from './config/list'
import OperationMenu from '@/components/OperationMenu'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import moment from 'moment'
import { downloadBlobFile } from '@/utils/functions'
import LocalUpload from '@/components/Upload/LocalUpload'
import userApi from "../../../api/modules/system/user";

export default {
  name: 'ModelList',
  mixins: [minxinDrawerUse],
  components: {
    tableEllipsis,
    HasNoPermissionTip,
    NewEditModel,
    NewEditBrand,
    STable,
    AuthButton,
    ManagedServicesList,
    OperationMenu,
    ConfigEcu,
    CarModelCodeSelect,
    LocalUpload,
    APopover,
    FilterBoxCollection,
    AuthText
  },
  computed: {
    ...mapState({
      newModelData: state => state.model.newModelData,
      rightDrawerEvent: state => state.model.rightDrawerEvent,
      configModelDataFrom: (state) => state.dict.configModelDataFromDictCode,
      instantUpdateTime: (state) => state.app.instantUpdateTime
    }),
    tbRowMenus () {
      const rowMenu = [
        {
          // 管理服务
          title: this.$t('managedServices'),
          key: 'manageService',
          auth: managePerms.model.serviceManage
        },
        {
          // 配置ecu
          title: this.$t('ecuConfig'),
          key: 'ecuConfig',
          auth: managePerms.model.configEcu
        },
        {
          // 编辑车型
          title: this.$t('edit'),
          key: 'handleAddEdit',
          auth: managePerms.model.edit
        },
        {
          // 删除车型
          title: this.$t('delete'),
          key: 'deleteList',
          // disabled(record) {
          //   return record.dataFrom === 'EXTERNAL';
          // },
          auth: managePerms.model.delete
        },
        {
          // 克隆
          title: '复制',
          key: 'copy',
          auth: managePerms.model.add
        }
      ]
      return rowMenu
    },
    queryParamsDesc() {
      let {brandId, code} = this.queryParam;
      let b = this.brandSeleList.find(value => value.id === brandId);
      return {
        brandId: b ? b.name : undefined,
        code: code ? this.queryParam.trimLevelName : undefined
      };
    }
  },
  data () {
    let data = {
      synchronizing: false,
      moment,
      createTime: null,
      managePerms,
      userList: [],
      tableData: [],
      selectedRows: [],
      selectedRowKeys: [],
      hideConfigModel: true, //隐藏配置车型信息，目前先不维护配置车型信息
      importFile:'',
      uploadRes:{
        fail: [],
        success: [],
        failCount: 0,
        successCount: 0,
      },
      importVisible: false,
      exporting: false,
      downloading: false,
      brandSeleList: [], // 品牌筛选
      recordData: {}, // 编辑信息
      // 查询参数
      queryParam: {},
      actions: {
        // 新建车型
        ccx: {
          method: 'handleAddEdit'
        }
      }
    };
    if (data.hideConfigModel) {
      data.columns = modelListTbColumns.filter(item => ['name', 'code'].indexOf(item.dataIndex) < 0);
    } else {
      data.columns= modelListTbColumns;
    }
    let cols = [...data.columns];
    cols.splice(modelListTbColumns.length - 8, 8);
    cols.push({
      title: '失败原因',
      dataIndex: 'message',
      width: 200,
      fixed: 'right',
      scopedSlots: { customRender: 'message' }
    })
    data.importFailColumns = cols
    data.importSuccessColumns = [...cols]
    data.importSuccessColumns.splice(cols.length - 1, 1)

    // 删除关联CE不展示
    data.importFailColumns.splice(5, 1)
    data.importSuccessColumns.splice(5, 1)
    return data
  },
  watch: {
    rightDrawerEvent (val) {
      const vm = this
      if (val === 'newBrand') {
        vm.handleAddEditBrand()
      }
    },
    importVisible (val) {
      if (!val) {
        this.importFile = '';
        this.uploadRes.fail=[];
        this.uploadRes.success=[];
      }
    }
  },
  created () {
    const actionObj = this.actions[this.$route.query.action]
    // 从别的页面跳转过来调用相应的功能
    if (actionObj && actionObj.method) {
      this[actionObj.method]()
    }
    this.filterItem()
  },
  mounted() {
    this.$store.dispatch('getConfigModelDataFromDictCodeData');
    this.$store.dispatch('getCompanyDictCodeData');
    this.$store.dispatch('getPowerTypeDictCodeData');
    this.$store.dispatch('getSaleAreaDictCodeData');
    this.getUsers();
  },
  methods: {
    sync() {
      this.synchronizing = true
      this.$api
        .syncEcuGcy()
        .then(res => {
          this.$message.success('同步完成');
        })
        .finally(() => {
          this.synchronizing = false
        })
    },
    getPopupContainer() {
      return document.body;
    },
    ...mapMutations([
      'SET_ModelRightDrawerEvent',
      // 'setDrawerConfig',
    ]),
    getUsers() {
      userApi.getUserPageData({pageSize:5000}).then(res => {
        this.userList = res.data;
      }).catch((e) => vm.$message.error("获取创建人信息失败！"))
    },
    getCheckboxProps(record) {
      return {
        props: {
          // disabled: record.dataFrom === 'EXTERNAL', // Column configuration not to be checked
          name: record.id,
        },
      }
    },
    onTableSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRowKeys.map(item => {
        return this.tableData[item.split("-")[1]];
      }).filter(row => row)
    },
    selectDateRange(date, dateString){
      this.queryParam.createTimeStart = dateString[0] ;
      this.queryParam.createTimeEnd = dateString[1] ;
      this.refreshData(true)
    },
    initiSelectValue () {
      this.queryParam = {
        createTimeStart: '',
        createTimeEnd: '',
      }
      this.createTime = undefined;
      this.refreshData(true)
    },
    getTbRowMenus (record) {
      return this.tbRowMenus.filter(item => {
        return !(item.disabled && item.disabled(record))
      })
    },
    // 列表操作
    doAction (key, record) {
      const vm = this
      vm[key](record)
    },
    // 筛选条件
    filterItem () {
      //   列表下拉框
      this.$api.getAllBrand().then(response => {
        this.brandSeleList = response.data
      }).catch((e) => vm.$message.error("获取车系失败！"))
      // this.$store.dispatch('getBrandFilterData')
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      this.tableData = [];
      this.selectedRows = [];
      this.selectedRowKeys = [];
      var apiPromise = vm.$api.getCarModelList({...parameter, ...JnqueryParam});
      return new Promise((resolve, reject) => {
        return apiPromise.then((res) => {
          if (res.data) {
            this.tableData = res.data;
          }
          resolve(res);
        }).catch(e => reject(e));
      });
    },
    exportXlsx() {
      this.exporting = true;
      this.$api.exportCarModelList( this.queryParam ).then((res) => {
        downloadBlobFile(res, '导出车型'+moment().format('YYYYMMDDHHmmss')+'.xlsx')
      }).finally(() => {
        this.exporting = false
      })
    },
    downloadTemplate() {
      this.downloading = true;
      this.$api.importCarModelListTemplate().then((res) => {
        downloadBlobFile(res, '车型导入模板.xlsx')
      }).finally(() => {
        this.downloading = false
      })
    },
    showFileObj (value) {
      const vm = this
      vm.importFile = value.name
      const formData = new FormData()
      formData.append('file', value)
      this.uploadRes.fail = [];
      this.uploadRes.failCount = 0;
      this.uploadRes.success = [];
      this.uploadRes.successCount = 0;
      vm.$api.importCarModelList(formData).then(res => {
        if (res.data) {
            /**
            * 款型级别数据改为配置车型数据，从而可以重用列表格式
            */
            let transTrimLeveToConfigModel = (resp) => {
              return resp.data.trimLevel[0].configModels.map((configModel) => {
                return {
                  name : configModel.name,
                  code : configModel.code,
                  publishCode : configModel.publishCode,
                  message : resp.message,
                  model : {
                    company : resp.data.company,
                    brandName : resp.data.brandId,
                    name : resp.data.name,
                    code : resp.data.code,
                    makeYear : resp.data.makeYear,
                    saleArea : resp.data.saleArea,
                    trimLevel : resp.data.trimLevel[0].trimLevel,
                    trimLevelCode : resp.data.trimLevel[0].trimLevelCode,
                    power : resp.data.trimLevel[0].power,
                  }
                }
              });
            };
          if(res.data.fail){
            res.data.fail.forEach((item) => {
              // vm.uploadRes.fail = [...vm.uploadRes.fail, ...configModels];
              // let configModels = transTrimLeveToConfigModel(item);
              vm.uploadRes.fail = [...vm.uploadRes.fail, {
                ...item.data,
                message : item.message,
              }];
            })
            vm.uploadRes.failCount = vm.uploadRes.fail.length;
            // 截取500条
            vm.uploadRes.fail.splice(500);
          }
          if(res.data.success){
            res.data.success.forEach((item) => {
              // let configModels = transTrimLeveToConfigModel(item);
              // vm.uploadRes.success = [...vm.uploadRes.success, ...configModels];
              vm.uploadRes.success = [...vm.uploadRes.success, item.data];
            })
            vm.uploadRes.successCount = vm.uploadRes.success.length;
            vm.uploadRes.success.splice(500);
          }
          if (vm.uploadRes.successCount === 0 && vm.uploadRes.failCount === 0) {
            vm.$message.error("没有数据！");
          }
          if (vm.uploadRes.successCount > 0) {
            this.refreshData(false);
          }
        }
      }).catch(() => {
        vm.importFile = ''
      })
    },
    copy (recordData) {
      console.log(recordData)
      console.log('recordData', 'records')
      if (recordData.length === 0) {
        this.$message.error("请选择要复制的数据！")
        return
      }
      if (recordData.length > 1) {
        this.$message.error("请选择要复制的一条数据！")
        return
      }
      let deepCopy = this.$commonFun.deepCopy(recordData[0])
      deepCopy.id = null;
      deepCopy.model.id=null;
      // this.SET_NEWMODEL_DATA(deepCopy);
      this.handleAddEdit(deepCopy);
    },
    // 新增 编辑车型
    handleAddEdit (recordData = {}, isBack = false) {
      const vm = this
      const buttons = this.getRightDrawerFooterButtons()
      const vars = { recordData, isBack }
      // eslint-disable-next-line max-len
      if (recordData.hasOwnProperty('model')) {
        vm.showRightDrawer(NewEditModel, vm.$t(recordData.id ? 'edit' : 'new') , buttons, 'medium', vars);
      } else {
        vm.showRightDrawerNoReset(NewEditModel, vm.$t(recordData.id ? 'edit' : 'new') , buttons, 'medium', vars);
        vm.setDrawerConfig({
        headerButtons:[]
      })
      }
      vm.SET_ModelRightDrawerEvent('newModel');
    },
    // 编辑和新增保存车型
    saveData (values) {
      const vm = this
      const apiObi = vm.getPamarsApi(values)
      return new Promise((resolve, reject) => {
        vm.$api[apiObi.apiStr](apiObi.paramsObj).then(res => {
          vm.refreshData(!values.id)
          // 清理备份
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 确定按钮的api和参数
    getPamarsApi (values) {
      let apiStr = ''
      let paramsObj = {}
      if (values.configTag) {
        // 配置ecu提交
        apiStr = 'putConfigEcu'
        paramsObj = { ecuVersions: values.ecuVersions }
      } else if (!values.configTag && values.id) {
        // 编辑车型
        const parmas = {
          id: values.trimLevel[0].configModels[0].id,
          publishCode: values.trimLevel[0].configModels[0].publishCode,
          modelId: values.trimLevel[0].id,
          modelName: values.name,
          saleArea: values.saleArea || '',
          power: values.trimLevel[0].power || '',
          company: values.company || '',
          brandId: values.brandId || '',
        }
        apiStr = 'editModel'
        paramsObj = parmas
      } else if (!values.configTag && !values.id) {
        // 新增车型
        apiStr = 'addModel'
        paramsObj = values
      }
      return { apiStr, paramsObj }
    },
    // 新增编辑品牌弹框
    handleAddEditBrand () {
      const vm = this
      const buttons = [{
        key: '',
        title: 'back',
        type: 'primary',
        name: 'backBtn',
        method: vm.backToModelEdit,
        callback: null,
        loading: false,
        disabled: false
      }]
      const headerButtons = [{
        type: '',
        method: vm.addBrand,
        iconCls: 'icon-xinjian',
        class: 'headerBtnClas'
      }]
      vm.setDrawerConfig({
        compName: NewEditBrand,
        title: vm.$t('editBrand'),
        footerButtons: buttons,
        headerButtons
      })
    },
    // 新增品牌
    addBrand (comp) {
      comp.addList()
    },
    // 返回编辑或新增车型页面
    backToModelEdit () {
      const vm = this
      vm.handleAddEdit(vm.newModelData, true)
    },
    // 批量删除
    deleteList (records, sucCallback) {
      if (!(records instanceof Array)) {
        records = [records];
      }
      if (records.length === 0) {
        this.$message.error("请选择要删除的数据！");
        return
      }
      const vm = this;
      this.$confirm({
        title: vm.$t('deleteModel'),
        //选中只展示款型信息，以后若要配置车型再增加配置车型信息
        content: vm.$t('deleteModelTip') + '(' + records.map(item => item.model.code + '[' + item.model.trimLevelCode + ']').join(', ') + ')',
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk () {
          let items = records.map(item => {
            return {
              modelId: item.model.id,
              configModelId: item.id,
            }
          });
          vm.$api.deleteCarModel({
            configModels: items
          }).then(response => {
            vm.$message.success(vm.$t('successfullyDelete'))
            if(sucCallback && typeof sucCallback === 'function'){
              sucCallback();
            }
            vm.refreshData(false) // 刷新页面
          });
        },
        onCancel () { }
      })
    },
    // 查看车型详情numType（关联零件or管理版本）
    showCarModelDetail (record, numType) {
      const vars = {
        id: record.model.id,
        numType: numType
      }
      this.showRightDrawer(ModelDetail, record.model.name + '-' + record.model.trimLevel, [], 'huge', vars)
    },
    manageService (recordData) {
      const vm = this
      const buttons = []
      const vars = { recordData: recordData.model }
      vm.showRightDrawer(ManagedServicesList, this.$t('managedServices'), buttons, 'huge', vars)
    },
    ecuConfig (recordData) {
      const vm = this
      const buttons = []
      const vars = { recordData: recordData.model }
      vm.showRightDrawer(ConfigEcu, this.$t('ecuConfig'), buttons, 'huge', vars)
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    }
  }
}
</script>
<style lang="less" scoped>
::v-deep .ant-form-item {
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
}
::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
</style>
